Option Explicit

' 执行sql格式化
Private Sub formatBtn_Click()
    ' 1. 检查: 如果原始 sql 为空，则退出
    If originSql.Value = "" Then
        Exit Sub
    End If

    ' 2. 创建配置对象
    Dim config As SqlFormatterConfiguration
    Set config = createConfig

    ' 3. 创建解析器
    Dim formatter As SqlFormatter
    Set formatter = New SqlFormatter
    formatter.Init config

    ' 4. 执行解析
    formatter.analyze originSql.Value

    ' 5. 写回格式化结果
    formattedSql.Value = formatter.getSql

    ' 6. 清除缓存
    UtilsPool.clearAllPool
End Sub

' 创建配置对象
Private Function createConfig() As SqlFormatterConfiguration
    Dim result As SqlFormatterConfiguration
    Set result = New SqlFormatterConfiguration

    With result
        ' ==============================
        ' 1. 设置对齐配置
        ' ==============================
        .firstConditionNeedFillSpace = firstConditionNeedFillSpace.Value
        .multiNestAlignmentStrSizeDiff = multiNestAlignmentStrSizeDiffVal.Value

        If alignmentLevelNoAlign.Value Then
            .alignmentLevel = SqlAlignmentLevel.NO_ALIGNMENT
        ElseIf alignmentLevelInternal.Value Then
            .alignmentLevel = SqlAlignmentLevel.INTERNAL
        ElseIf alignmentLevelAllLevel.Value Then
            .alignmentLevel = SqlAlignmentLevel.ALL_LEVEL
        End If

        .elemNestLevelPrefixSpaceCount = elemNestLevelPrefixSpaceCountVal.Value

        If alignmentPositionOperatorLeft.Value Then
            .alignmentPosition = SqlAlignmentPosition.OPERATOR_LEFT
        ElseIf alignmentPositionOperatorRight.Value Then
            .alignmentPosition = SqlAlignmentPosition.OPERATOR_RIGHT
        End If

        ' ==============================
        ' 2. 其他的配置
        ' ==============================
        .insertColListNeedLineBreakAfterComma = insertColListNeedLineBreakAfterComma.Value
        .needSqlEndSemicolon = needSqlEndSemicolon.Value

        If lineBreakLf.Value Then
            .lineBreak = vbLf
        ElseIf lineBreakCrLf.Value Then
            .lineBreak = vbCrLf
        End If
    End With

    Set createConfig = result
End Function
